package 剑指offer.链表;

/**
 * 给你两个排序的有序链表，把他组成一个新的排序链表
 */
public class 第25题合并两个排序的链表 {

    static class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode Merge1(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }
        if (list1.val <= list2.val) {
            list1.next = Merge1(list1.next, list2);
            return list1;
        } else {
            list2.next = Merge1(list1, list2.next);
            return list2;
        }
    }

    public static ListNode Merge2(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }
        ListNode ans = new ListNode(0);
        // ans 一直调用 next 方法会导致指向 ans 的指针无法指向头部。需要一个指针帮助他
        ListNode help = ans;
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                ans.next = list1;
                list1 = list1.next;
                ans = ans.next;
            } else {
                ans.next = list2;
                list2 = list2.next;
                ans = ans.next;
            }
        }
        if (list1 != null) {
            ans.next = list1;
        }
        if (list2 != null) {
            ans.next = list2;
        }
        return help.next;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l3 = new ListNode(3);
        ListNode l5 = new ListNode(5);
        l1.next = l3;
        l3.next = l5;

        ListNode l2 = new ListNode(2);
        ListNode l4 = new ListNode(4);
        ListNode l6 = new ListNode(6);
        l2.next = l4;
        l4.next = l6;

        ListNode ans = Merge2(l1, l2);
        System.out.println();
    }
}
